<template>
  <div>
    <!-- 表格1 -->
    <div class="item">
      <el-form>
        <div class="title">
          <span class="title-icon" />
          <span class="title-text">回收商品列表</span>
          <el-button type="primary" style="width: 70px; margin-left: 10px;" size="mini" @click="addRow('tableData01')">添加</el-button>
        </div>
        <lb-table
          ref="lbTable"
          border
          highlight-current-row
          element-loading-text="加载中"
          :column="tableData01.column"
          :data="recycleGoodsList"
          :pagination="false"
          :summary-method="getSummariesRecycle"
          show-summary
        />
      </el-form>
    </div>

    <!-- 表格2 -->
    <div class="item">
      <el-form>
        <div class="title">
          <span class="title-icon" />
          <span class="title-text">置换商品列表</span>
          <el-button type="primary" style="width: 70px; margin-left: 10px;" size="mini" @click="addRow('tableData02')">添加</el-button>
        </div>
        <lb-table
          ref="lbTable"
          border
          highlight-current-row
          element-loading-text="加载中"
          :column="tableData02.column"
          :data="substituteGoodsList"
          :summary-method="getSummariesRecycle"
          :pagination="false"
          show-summary
        />
      </el-form>
    </div>
    <!-- 红字 -->
    <div class="red">
      <div class="red01">
        费用金额：{{ cost }}
      </div>
      <div>
        费用金额 = 置换合计 - 回收合计，正数表示收入，负数表示支出
      </div>
    </div>
  </div>
</template>

<script>
  import { formatColumnMap } from '@/utils'
  import { goodsTypeQueryList, queryGoodsListAll, queryMap } from '@/api'
  import { keepDotLength } from '@/utils/math'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'

  export default {
    name: 'EditableTable',
    props: {
      temp: {
        type: Object
      }
    },
    data() {
      return {
        tableData01: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              prop: 'gtId',
              label: '商品分类',
              width: 180,
              render: (h, scope) => {
                return (
                  <div>
                    {scope.row._edit ? (
                      <el-select
                        size='mini'
                        style='width: 130px'
                        placeholder='请选择'
                        value={scope.row.gtId}
                        onChange={value => this.dataChange(scope.$index, 'gtId', value, 'tableData01')}
                      >
                        {this.goodsTypeListAll.map(item => (
                          <el-option key={item.gtId} value={item.gtId} label={item.gtName} />
                        ))}
                      </el-select>
                    ) : (<span>{scope.row.gtName}</span>)}
                  </div>
                )
              }
            },
            {
              prop: 'goodsId',
              label: '商品名称',
              width: 180,
              render: (h, scope) => {
                return (
                  <div>
                    {scope.row._edit ? (
                      <el-select
                        size='mini'
                        style='width: 130px'
                        placeholder='请选择'
                        value={scope.row.goodsId}
                        onChange={value => this.dataChange(scope.$index, 'goodsId', value, 'tableData01')}
                      >
                        {this.goodsListAll.map(item => (
                          <el-option key={item.goodsId} value={item.goodsId} label={item.goodsName} />
                        ))}
                      </el-select>
                    ) : (<span>{scope.row.goodsName}</span>)}
                  </div>
                )
              }
            },
            {
              prop: 'specName',
              label: '规格型号',
              width: 100
            },
            {
              prop: 'gdStatus',
              label: '状态',
              width: 110,
              render: (h, { row, $index, column }) => {
                return (
                  <div>
                    {row._edit ? (
                      <el-select size='mini' value={row[column.property]} onChange={(val) => { row[column.property] = val }}>
                        {this.gdStatusMap.map((option) => {
                          return (
                            <el-option size='mini' label={option.desc} value={option.value} key={option.value}></el-option>
                          )
                        })}
                      </el-select>
                    ) : (<span>{row[column.property] ? formatColumnMap(this.gdStatusMap, 'value', row[column.property], 'desc') : ''}</span>)}
                  </div>
                )
              }
            },
            {
              prop: 'unitName',
              label: '单位',
              align: 'center',
              width: 50
            },
            {
              prop: 'goodsCount',
              align: 'right',
              label: '回收数量',
              width: 100,
              render: (h, scope) => {
                return (
                  <div>
                    {scope.row._edit ? (
                      <el-input-number size='mini' controls={false} max={99999} precision={0} value={scope.row[scope.column.property]} onChange={value => this.dataChange(scope.$index, 'goodsCount', value, 'tableData01')} disabled={scope.row.goodsCountDisabled}></el-input-number>
                    ) : (<span>{scope.row[scope.column.property]}</span>)}
                  </div>
                )
              }
            },
            {
              prop: 'netWeight',
              align: 'right',
              label: '回收重量',
              width: 100,
              render: (h, scope) => {
                return (
                  <div>
                    {scope.row._edit ? (
                      <el-input-number size='mini' controls={false} max={99999} precision={2} value={scope.row[scope.column.property]} onChange={value => this.dataChange(scope.$index, 'netWeight', value, 'tableData01')} disabled={scope.row.netWeightDisabled} onBlur={this.inputFormat}></el-input-number>
                    ) : (<span>{scope.row[scope.column.property]}</span>)}
                  </div>
                )
              }
            },
            {
              prop: 'price',
              align: 'right',
              label: '回收单价',
              width: 100,
              render: (h, scope) => {
                return (
                  <div>
                    {scope.row._edit ? (
                      <el-input-number size='mini' controls={false} min={0} max={99999} precision={2} value={scope.row[scope.column.property]} onChange={value => this.dataChange(scope.$index, 'price', value, 'tableData01')} onBlur={this.inputFormat}></el-input-number>
                    ) : (<span>{scope.row[scope.column.property]}</span>)}
                  </div>
                )
              }
            },
            {
              prop: 'amount',
              align: 'right',
              label: '回收总价',
              width: 100,
              render: (h, scope) => {
                return (
                  <div>
                    {scope.row._edit ? (
                      <el-input-number size='mini' controls={false} min={0} max={99999} precision={2} value={scope.row[scope.column.property]} onChange={value => this.dataChange(scope.$index, 'amount', value, 'tableData01')} onBlur={this.inputFormat}></el-input-number>
                    ) : (<span>{scope.row[scope.column.property]}</span>)}
                  </div>
                )
              }
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 90,
              render: (h, scope) => {
                return (
                  scope.row._edit ? <div>
                    <el-link type='primary' size='mini' onClick={() => this.saveRow(scope, 'tableData01')}>
                      保存
                    </el-link>
                    <el-link size='mini' type='danger' onClick={() => this.del(scope, 'tableData01')}>
                      删除
                    </el-link>
                  </div> : <div>
                    <el-link type='primary' size='mini' onClick={() => this.editRow(scope)}>
                      编辑
                    </el-link>
                    <el-link size='mini' type='danger' onClick={() => this.del(scope, 'tableData01')}>
                      删除
                    </el-link>
                  </div>
                )
              }
            }
          ],
          data: []
        },
        tableData02: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              prop: 'gtId',
              label: '商品分类',
              width: 180,
              render: (h, scope) => {
                return (
                  <div>
                    {scope.row._edit ? (
                      <el-select
                        size='mini'
                        style='width: 130px'
                        placeholder='请选择'
                        value={scope.row.gtId}
                        onChange={value => this.dataChange(scope.$index, 'gtId', value, 'tableData02')}
                      >
                        {this.goodsTypeListAll.map(item => (
                          <el-option key={item.gtId} value={item.gtId} label={item.gtName} />
                        ))}
                      </el-select>
                    ) : (<span>{scope.row.gtName}</span>)}
                  </div>
                )
              }
            },
            {
              prop: 'goodsId',
              label: '商品名称',
              width: 180,
              render: (h, scope) => {
                return (
                  <div>
                    {scope.row._edit ? (
                      <el-select
                        size='mini'
                        style='width: 130px'
                        placeholder='请选择'
                        value={scope.row.goodsId}
                        onChange={value => this.dataChange(scope.$index, 'goodsId', value, 'tableData02')}
                      >
                        {this.goodsListAll.map(item => (
                          <el-option key={item.goodsId} value={item.goodsId} label={item.goodsName} />
                        ))}
                      </el-select>
                    ) : (<span>{scope.row.goodsName}</span>)}
                  </div>
                )
              }
            },
            {
              prop: 'specName',
              label: '规格型号',
              width: 100
            },
            {
              prop: 'gdStatus',
              label: '状态',
              width: 110,
              render: (h, { row, $index, column }) => {
                return (
                  <div>
                    {row._edit ? (
                      <el-select size='mini' value={row[column.property]} onChange={(val) => { row[column.property] = val }}>
                        {this.gdStatusMap.map((option) => {
                          return (
                            <el-option size='mini' label={option.desc} value={option.value} key={option.value}></el-option>
                          )
                        })}
                      </el-select>
                    ) : (<span>{row[column.property] ? formatColumnMap(this.gdStatusMap, 'value', row[column.property], 'desc') : ''}</span>)}
                  </div>
                )
              }
            },
            {
              prop: 'unitName',
              label: '单位',
              align: 'center',
              width: 50
            },
            {
              prop: 'goodsCount',
              align: 'right',
              label: '置换数量',
              width: 100,
              render: (h, scope) => {
                return (
                  <div>
                    {scope.row._edit ? (
                      <el-input-number size='mini' controls={false} max={99999} precision={0} value={scope.row[scope.column.property]} onChange={value => this.dataChange(scope.$index, 'goodsCount', value, 'tableData02')} disabled={scope.row.goodsCountDisabled}></el-input-number>
                    ) : (<span>{scope.row[scope.column.property]}</span>)}
                  </div>
                )
              }
            },
            {
              prop: 'netWeight',
              align: 'right',
              label: '置换重量',
              width: 100,
              render: (h, scope) => {
                return (
                  <div>
                    {scope.row._edit ? (
                      <el-input-number size='mini' controls={false} max={99999} precision={2} value={scope.row[scope.column.property]} onChange={value => this.dataChange(scope.$index, 'netWeight', value, 'tableData02')} disabled={scope.row.netWeightDisabled} onBlur={this.inputFormat}></el-input-number>
                    ) : (<span>{scope.row[scope.column.property]}</span>)}
                  </div>
                )
              }
            },
            {
              prop: 'price',
              align: 'right',
              label: '置换单价',
              width: 100,
              render: (h, scope) => {
                return (
                  <div>
                    {scope.row._edit ? (
                      <el-input-number size='mini' controls={false} min={0} max={99999} precision={2} value={scope.row[scope.column.property]} onChange={value => this.dataChange(scope.$index, 'price', value, 'tableData02')} onBlur={this.inputFormat}></el-input-number>
                    ) : (<span>{scope.row[scope.column.property]}</span>)}
                  </div>
                )
              }
            },
            {
              prop: 'amount',
              align: 'right',
              label: '置换总价',
              width: 100,
              render: (h, scope) => {
                return (
                  <div>
                    {scope.row._edit ? (
                      <el-input-number size='mini' controls={false} min={0} max={99999} precision={2} value={scope.row[scope.column.property]} onChange={value => this.dataChange(scope.$index, 'amount', value, 'tableData02')} onBlur={this.inputFormat}></el-input-number>
                    ) : (<span>{scope.row[scope.column.property]}</span>)}
                  </div>
                )
              }
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 90,
              render: (h, scope) => {
                return (
                  scope.row._edit ? <div>
                    <el-link type='primary' size='mini' onClick={() => this.saveRow(scope, 'tableData02')}>
                      保存
                    </el-link>
                    <el-link size='mini' type='danger' onClick={() => this.del(scope, 'tableData02')}>
                      删除
                    </el-link>
                  </div> : <div>
                    <el-link type='primary' size='mini' onClick={() => this.editRow(scope)}>
                      编辑
                    </el-link>
                    <el-link size='mini' type='danger' onClick={() => this.del(scope, 'tableData02')}>
                      删除
                    </el-link>
                  </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    computed: {
      // 费用金额
      cost: function() {
        const recycleAmount = this.recycleGoodsList.reduce((pre, cur) => pre + cur.amount, 0)
        const replaceAmount = this.substituteGoodsList.reduce((pre, cur) => pre + cur.amount, 0)
        return Number((replaceAmount || 0) - (recycleAmount || 0)).toFixed(2)
      },
      recycleGoodsList: function() {
        if (this.temp.recycleGoodsList) this.tableData01.data.concat(this.temp.recycleGoodsList)
        return this.tableData01.data
      },
      substituteGoodsList: function() {
        if (this.temp.substituteGoodsList) this.tableData02.data.concat(this.temp.substituteGoodsList)
        return this.tableData02.data
      }
    },
    async created() {
      await Promise.all([this.getGoodsTypeListAll(), this.queryOptionsMap()])
    },
    methods: {
      // 查询所有商品分类列表
      async getGoodsTypeListAll() {
        const res = await goodsTypeQueryList()
        this.goodsTypeListAll = res.data
        const match = res.data.filter(item => item.gtFlag === 2)
        this.goodsTypeChange(match[0].gtId)
      },
      async dataChange(index, key, value, name) {
        const { data } = this[name]
        data[index][key] = value
        let goods = this.goodsListAll.find(item => item.goodsId === data[index].goodsId)
        if (key === 'gtId') {
          data[index].goodsId = ''
          data[index].gdStatus = ''
          const res = await queryGoodsListAll({
            gtId: value
          })
          this.goodsListAll = res.data
        } else if (key === 'goodsId') {
          data[index].gdStatus = ''
          goods = this.goodsListAll.find(item => item.goodsId === value)
          if (goods) data[index].goodsName = goods.goodsName
          const row = goods
          if (row) {
            row.tempGdStatus = goods.gdStatus
            data[index].pricingMode = row.pricingMode
            let datas = JSON.parse(JSON.stringify(this.gdStatusMapOrigin))
            if (row.tempGdStatus) {
              const realItems = []
              let lightStatus = null
              for (const i in datas) {
                const item = datas[i]
                if ((row.tempGdStatus & 1 << item.value) > 0) {
                  if (lightStatus == null) {
                    lightStatus = item
                  }
                  if (item.value === 2) {
                    lightStatus = item
                  }
                  realItems.push(item)
                }
              }
              this.gdStatusMap = realItems
              if (realItems.length > 0) {
                data[index].gdStatus = realItems[0].value
              }
            } else {
              if (row.pricingMode === 2) {
                if (row.tempGdStatus > 0) {
                  datas = [{ id: 6, text: '正常' }]
                  this.gdStatusMap = datas
                  data[index].gdStatus = datas[0].id
                }
              } else {
                this.gdStatusMap = datas
                data[index].gdStatus = datas[0].id
              }
            }
            if (row.pricingMode === 1) {
              data[index].netWeight = undefined
              data[index].netWeightDisabled = true
              data[index].goodsCountDisabled = false
              data[index].goodsCount = 1
            } else {
              data[index].goodsCount = undefined
              data[index].goodsCountDisabled = true
              data[index].netWeightDisabled = false
              data[index].netWeight = 0
            }
            data[index].price = 0
            data[index].amount = 0
          }
        } else if (key === 'price') {
          data[index].amount = goods && goods.pricingMode === 1 ? data[index].price * data[index].goodsCount : data[index].price * data[index].netWeight
        } else if (key === 'amount') {
          if (goods && goods.pricingMode === 1) {
            data[index].price = Number((data[index].amount || 0) / (data[index].goodsCount || 0)).toFixed(2)
          } else {
            data[index].price = Number((data[index].amount || 0) / (data[index].netWeight || 0)).toFixed(2)
          }
        } else if (key === 'goodsCount') {
          if (goods && goods.pricingMode === 1) data[index].amount = data[index].price * data[index].goodsCount
          else data[index].amount = data[index].price * data[index].netWeight
        }
      },
      // 根据商品分类查询商品列表
      async goodsTypeChange(gtId) {
        const res = await queryGoodsListAll({
          gtId
        })
        this.goodsListAll = res.data
        this.goodsListAllOrigin = res.data
      },
      // 添加
      addRow(name) {
        this.goodsListAll = this.goodsListAllOrigin
        const row = {}
        for (let i = 0; i < this.goodsTypeListAll.length; i++) {
          if (this.goodsTypeListAll[i].gtFlag === 2) {
            row.gtId = this.goodsTypeListAll[i].gtId // 商品分类
            row.gtName = this.goodsTypeListAll[i].gtName
            row.goodsId = '' // 商品名称
            row.goodsName = ''
            row.specCode = '' // 规格型号
            row.specName = ''
            row.gdStatus = '' // 状态
            row.unitId = '' // 单位
            row.unitName = ''
            row.goodsCount = undefined // 回收数量
            row.netWeight = undefined // 回收重量
            row.price = 0 // 回收单价
            row.amount = 0 // 回收总价
            row.goodsCountDisabled = false
            row.netWeightDisabled = false
            row.pricingMode = ''
            break
          }
        }
        this[name].data.push(row)
      },
      async editRow(scope) {
        this.$set(scope.row, '_edit', true)
        // const selectedGoods = scope.row.goodsId
        // if (selectedGoods) {
        //   if (this.corpSettingData.sp3 >> 6 & 0x01) {
        //     if (selectedGoods.pricingMode === 2) {
        //       this.gdStatusMap = [{ value: 6, text: '正常' }]
        //     } else if (selectedGoods.gtFlag <= 2) {
        //       const datas = this.gdStatusMapOrigin
        //       if (selectedGoods.gdStatus) {
        //         const realItems = []
        //         for (const i in datas) {
        //           const item = datas[i]
        //           if ((selectedGoods.gdStatus & 1 << item.value) > 0) {
        //             realItems.push(item)
        //           }
        //         }
        //         this.gdStatusMap = realItems
        //       } else {
        //         this.gdStatusMap = datas
        //       }
        //     }
        //   } else {
        //     if (selectedGoods.gtFlag === 3 || selectedGoods.pricingMode === 2) {
        //       this.gdStatusMap = [{ value: 6, text: '正常' }]
        //     } else if (selectedGoods.gtFlag <= 2) {
        //       const datas = this.gdStatusMapOrigin
        //       if (selectedGoods.gdStatus) {
        //         const realItems = []
        //         for (const i in datas) {
        //           const item = datas[i]
        //           if ((selectedGoods.gdStatus & 1 << item.value) > 0) {
        //             realItems.push(item)
        //           }
        //         }
        //         this.gdStatusMap = realItems
        //       } else {
        //         this.gdStatusMap = datas
        //       }
        //     }
        //   }
        // }
        // if (scope.row.pricingMode === 1) {
        //   scope.row.netWeightDisabled = true
        //   scope.row.goodsCountDisabled = false
        // } else {
        //   scope.row.goodsCountDisabled = true
        //   scope.row.netWeightDisabled = false
        // }
      },
      saveRow(scope, name) {
        if (!scope.row.goodsId) {
          this.$message.error('请选择商品')
          return
        }
        const goods = this.goodsListAll.find(item => item.goodsId === scope.row.goodsId)
        if (goods.pricingMode === 1) {
          if (!scope.row.goodsCount) {
            this.$message.error('请填写的回收数量')
            return
          }
          scope.row.netWeight = 0
        } else {
          if (!scope.row.netWeight) {
            this.$message.error('请填写回收重量')
            return
          }
          scope.row.goodsCount = 0
        }
        if (name === 'tableData02') {
          if (!scope.row.gdStatus) {
            this.$message.error('请选择状态')
            return
          }
          if (scope.row.pricingMode === 2) {
            if (!scope.row.netWeight) {
              this.$message.error('请填写置换重量')
              return
            }
          } else {
            if (!scope.row.goodsCount) {
              this.$message.error('请填写置换数量')
              return
            }
          }
        }
        if (!scope.row.amount) {
          scope.row.amount = 0
        }
        this.$set(scope.row, '_edit', false)
        this.$set(this[name].data, scope.$index, JSON.parse(JSON.stringify(scope.row)))
      },
      del(scope, name) {
        this[name].data.splice(scope.$index, 1)
      },
      // 合计方法
      getSummariesRecycle(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 2) {
            sums[index] = '合计'
            return
          }
          if (['gtId', 'specName', 'gdStatus', 'unitName', 'netWeight', 'price'].includes(column.property)) {
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          }
        })
        if (!sums[6]) sums[6] = (0).toFixed(2) // 回收数量
        if (!sums[7]) sums[7] = (0).toFixed(2) // 回收重量
        sums[7] = Number(sums[7]).toFixed(2)
        sums[9] = sums[9] ? Number(sums[9]).toFixed(2) : (0).toFixed(2)
        return sums
      },
      inputFormat(e) {
        e.target.value = keepDotLength(e.target.value)
      },
      // 查询枚举
      async queryOptionsMap() {
        const res = await mergeAsyncFunc(queryMap, { enumName: 'GdStatus' })
        this.gdStatusMap = res.data // 商品状态
        this.gdStatusMapOrigin = res.data // 商品状态
      }
    }
  }
</script>

<style lang="scss" scoped>
.item {
  margin-bottom: 30px;
  .title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .title-icon {
      display: inline-block;
      width: 4px;
      height: 18px;
      margin-right: 6px;
      background: #01999f;
    }
    .title-text {
      font-family: Microsoft YaHei, Microsoft YaHei-Bold;
      font-size: 14px;
      font-weight: 700;
      color: #01999f;
    }
  }
  &:last-child {
    margin-bottom: 0;
  }
  .content {
    margin-bottom: 30px;
  }
}
.red {
  margin-top: 10px;
  color: red;
  .red01 {
    margin-bottom: 10px;
    font-size: 18px;
    font-weight: bold;
  }
}
</style>
